// 1. 引入要用到的api defineStore
import { defineStore } from 'pinia';
import type { CategoryStore } from '@/api/product/model/categoryModel';

// 引入接口函数
import {
  reqGetCategory1ListData,
  reqGetCategory2ListData,
  reqGetCategory3ListData,
} from '@/api/product/category';
// 2. 创建模块对象
export const useCategoryListStore = defineStore('categoryList', {
  state: (): CategoryStore => {
    return {
      // 以下三个属性用于收集用户真正选择的分类的id
      category1Id: undefined,
      category2Id: undefined,
      category3Id: undefined,

      // 以下三个数组用于存储服务器响应回来的分类数据
      category1List: [],
      category2List: [],
      category3List: [],
    };
  },
  actions: {
    // 1. 获取一级分类数据
    async getCategory1ListData() {
      const result = await reqGetCategory1ListData();
      this.category1List = result;
    },

    // 2. 获取二级分类数据
    async getCategory2ListData(category1Id: number) {
      this.category1Id = category1Id;
      //如果一级分类的id改变了，那么二三级也要重新设置为undefined
      this.category2Id = undefined;
      this.category3Id = undefined;
      this.category3List = []; //将三级列表也要清空
      //然后再去发送请求 获取二级数据
      this.category2List = await reqGetCategory2ListData(category1Id);
    },

    //3.获取三级分类数据
    async getCategory3ListData(category2Id: number) {
      this.category2Id = category2Id;
      //重置三级id
      this.category3Id = undefined;
      this.category3List = await reqGetCategory3ListData(category2Id);
    },

    //4.设置三级分类ID
    setCategory3Id(category3Id: number) {
      this.category3Id = category3Id;
    },
  },
});
